/*
 * Created by SharpDevelop.
 * User: fatman
 * Date: 10/27/2008
 * Time: 3:39 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;

namespace CUALib
{
	/// <summary>
	/// Description of TextBox.
	/// </summary>
	public static class TextParser
	{

		public static string ExtractActualString(ConsoleKeyInfo cki, string original)
		{
			if (cki.Key == ConsoleKey.Backspace)
			{
				if (original.Length > 0)
					original = original.Substring(0, original.Length - 1);
			}
			else
			{
				original += ExtractActualString(cki);
			}
			return original;
		}
		public static string ExtractActualString(ConsoleKeyInfo cki)
		{
			if (cki.KeyChar >= 0x20)
				return cki.KeyChar.ToString();
			return string.Empty;
		}

	}

	public class TextBox : PanelBase
	{
		public TextBox(bool consoleExists)
			: base(consoleExists)
		{


		}


		public override bool ReceiveEvent(ConsoleKeyInfo cki)
		{

			if (Focused)
			{

				
				_fullText = TextParser.ExtractActualString(cki, this._fullText);

				int len =  Math.Min(_fullText.Length, Width-1);
				if (len > 0 && len < _fullText.Length)
				{
					base.Text = _fullText.Substring(_fullText.Length - len);
				}
				else
				{
					base.Text = _fullText;
				}

				

				Redraw();
				Rectangle ab = AbsoluteBounds;
				Console.CursorVisible = true;
				Console.SetCursorPosition(ab.X + len + 1, ab.Y + 1);
			}
			return base.ReceiveEvent(cki);

		}

		public override bool Focused
		{
			get { return base.Focused; }
			set
			{

				base.Focused = value;
				if (value)
				{
					Rectangle ab = AbsoluteBounds;
					Console.CursorVisible = true;
					Console.SetCursorPosition(ab.X + 1, ab.Y + 1);

				}
				else
				{
					Console.CursorVisible = false;
				}

			}
		}


		private string _fullText;
		public override string Text
		{
			get
			{
				return base.Text;
			}
			set
			{
				base.Text = value;
				_fullText = value;
			}
		}
		

	}
}
